<template>
  <div class="chat-dialog" v-if="visible" @click.stop>
    <div class="chat-header">
      <div class="user-info">
        <img :src="targetUser.avatar" alt="用户头像" class="avatar">
        <span class="username">{{ targetUser.username }}</span>
      </div>
      <div class="close-btn" @click="close">×</div>
    </div>
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" 
           :class="['message', message.from_userId === currentUserId ? 'sent' : 'received']">
        <div class="message-content">{{ message.content }}</div>
        <div class="message-time">{{ message.createdAt | parseTime }}</div>
      </div>
      <div v-if="messages.length === 0" class="no-messages">
        {{ $t('chat.noMessages') }}
      </div>
    </div>
    <div class="chat-input">
      <textarea 
        v-model="messageText" 
        :placeholder="$t('chat.inputPlaceholder')"
        @keyup.enter="sendMessage"
      ></textarea>
      <button @click="sendMessage">{{ $t('chat.send') }}</button>
    </div>
  </div>
</template>

<script>
import websocketService from '@/utils/websocket';
import { getChatHistory, markAsRead } from '@/api/chat';

export default {
  name: 'ChatDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    targetUser: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      messages: [],
      messageText: '',
      currentUserId: localStorage.getItem('userId') || '',
      loading: false
    };
  },
  watch: {
    visible(val) {
      if (val && this.targetUser.userId) {
        this.loadChatHistory();
        this.markMessagesAsRead();
      }
    },
    messages() {
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    }
  },
  mounted() {
    websocketService.on('message', this.handleNewMessage);
    
    // 点击其他区域关闭聊天窗口
    document.addEventListener('click', this.handleOutsideClick);
  },
  beforeDestroy() {
    websocketService.off('message', this.handleNewMessage);
    document.removeEventListener('click', this.handleOutsideClick);
  },
  methods: {
    handleOutsideClick() {
      this.$emit('update:visible', false);
    },
    close() {
      this.$emit('update:visible', false);
    },
    async loadChatHistory() {
      if (!this.targetUser.userId) return;
      
      this.loading = true;
      try {
        const res = await getChatHistory({
          targetUserId: this.targetUser.userId
        });
        
        if (res.code === 200) {
          this.messages = res.data || [];
        }
      } catch (error) {
        console.error('获取聊天历史失败:', error);
      } finally {
        this.loading = false;
      }
    },
    async markMessagesAsRead() {
      if (!this.targetUser.userId) return;
      
      try {
        await markAsRead({
          fromUserId: this.targetUser.userId
        });
      } catch (error) {
        console.error('标记消息已读失败:', error);
      }
    },
    handleNewMessage(data) {
      // 只处理与当前聊天对象相关的消息
      if (data.type === 'chat' && 
         (data.from_userId === this.targetUser.userId || 
          data.to_userId === this.targetUser.userId)) {
        this.messages.push(data);
        
        // 如果是收到的消息，标记为已读
        if (data.from_userId === this.targetUser.userId) {
          this.markMessagesAsRead();
        }
      }
    },
    sendMessage() {
      if (!this.messageText.trim() || !this.targetUser.userId) return;
      
      const message = {
        type: 'chat',
        from_userId: this.currentUserId,
        from_username: localStorage.getItem('username') || '',
        to_userId: this.targetUser.userId,
        to_username: this.targetUser.username,
        content: this.messageText.trim(),
        createdAt: new Date().toISOString()
      };
      
      const sent = websocketService.send(message);
      if (sent) {
        // 本地添加消息
        this.messages.push(message);
        this.messageText = '';
      } else {
        this.$message.error(this.$t('chat.sendFailed'));
      }
    },
    scrollToBottom() {
      if (this.$refs.messagesContainer) {
        this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
      }
    }
  }
};
</script>

<style scoped lang="less">
.chat-dialog {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 320px;
  height: 400px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  z-index: 1000;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #8fd0cc;
  color: #fff;
  
  .user-info {
    display: flex;
    align-items: center;
    
    .avatar {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      margin-right: 10px;
    }
    
    .username {
      font-weight: bold;
    }
  }
  
  .close-btn {
    font-size: 24px;
    cursor: pointer;
    
    &:hover {
      color: #f0f0f0;
    }
  }
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
  
  .message {
    margin-bottom: 15px;
    max-width: 80%;
    
    &.sent {
      margin-left: auto;
      
      .message-content {
        background-color: #8fd0cc;
        color: #fff;
        border-radius: 10px 0 10px 10px;
      }
    }
    
    &.received {
      margin-right: auto;
      
      .message-content {
        background-color: #fff;
        color: #333;
        border-radius: 0 10px 10px 10px;
      }
    }
    
    .message-content {
      padding: 10px;
      word-break: break-word;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
    
    .message-time {
      font-size: 12px;
      color: #999;
      margin-top: 5px;
      text-align: right;
    }
  }
  
  .no-messages {
    text-align: center;
    color: #999;
    margin-top: 20px;
  }
}

.chat-input {
  padding: 10px;
  border-top: 1px solid #eee;
  display: flex;
  
  textarea {
    flex: 1;
    height: 40px;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 8px;
    resize: none;
    outline: none;
    
    &:focus {
      border-color: #8fd0cc;
    }
  }
  
  button {
    width: 60px;
    margin-left: 10px;
    background-color: #8fd0cc;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    
    &:hover {
      background-color: darken(#8fd0cc, 10%);
    }
  }
}

@media (max-width: 600px) {
  .chat-dialog {
    width: 90%;
    height: 70%;
    bottom: 10px;
    right: 5%;
  }
}
</style>